package top.saplf.sileny.reader.network

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.view.View
import im.delight.android.webview.AdvancedWebView
import kotlinx.android.synthetic.main.activity_network_article_view.*
import me.eugeniomarletti.extras.intent.IntentExtra
import me.eugeniomarletti.extras.intent.base.String
import top.saplf.sileny.R
import top.saplf.sileny.base.ui.IActivity


/**
 * @author saplf
 */

class NetworkArticleViewActivity
    : AppCompatActivity(), IActivity, AdvancedWebView.Listener {

    companion object {
        var Intent.uri: String by IntentExtra.String("")
        var Intent.desc: String by IntentExtra.String("")
    }

    override fun onLayoutRes(): Int = R.layout.activity_network_article_view

    override fun onViewCreated(savedInstanceState: Bundle?) {
        webView.loadUrl(intent.uri)
        webView.setListener(this, this)
        toolbar.text = intent.desc
        progress.visibility = View.VISIBLE
    }

    @SuppressLint("NewApi")
    override fun onPause() {
        webView.onPause()
        super.onPause()
    }

    override fun onDestroy() {
        webView.onDestroy()
        super.onDestroy()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent) {
        super.onActivityResult(requestCode, resultCode, intent)
        webView.onActivityResult(requestCode, resultCode, intent)
    }

    override fun onBackPressed() {
        if (!webView.onBackPressed()) {
            return
        }
        super.onBackPressed()
    }

    override fun onPageStarted(url: String, favicon: Bitmap?) {
        val uri = Uri.parse(url)
        uri.scheme?.run {
            if (this != "http" && this != "https") {
                startActivity(Intent().apply {
                    data = uri
                })
            }
        }
    }

    override fun onPageFinished(url: String) {
        if (progress.visibility == View.VISIBLE) {
            progress.visibility = View.GONE
        }
    }

    override fun onPageError(errorCode: Int, description: String?, failingUrl: String) {}

    override fun onDownloadRequested(url: String, suggestedFilename: String, mimeType: String, contentLength: Long, contentDisposition: String, userAgent: String) {}

    override fun onExternalPageRequest(url: String) {}
}
